﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

using H2.NET.Controls;
using H2.NET.Business;
using H2.NET.Data.Common;

using System.IO;
using H2.NET.Data.Exceller;

namespace H2.NET.Web.Pages.SPM
{
    public partial class InvoiceHolding : TaskPage 
    {
        #region 属性 Public

        private bool IsLoaded
        {
            get
            {
                return ViewState["IsLoaded"] == null ? false : (bool)ViewState["IsLoaded"];
            }
            set { ViewState["IsLoaded"] = value; }
        }
        private bool Status
        {
            get
            {
                return ViewState["Status"] == null ? false : (bool)ViewState["Status"];
            }
            set { ViewState["Status"] = value; }
        }
        public string Key
        {
            get
            {
                return ViewState["Key"] == null ? "" : (string)ViewState["Key"];

            }
            set { ViewState["Key"] = value; }
        }
        #endregion

        #region 事件 Page_Load(页面加载)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>王春花 (Carrie,Wang) 
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            bool flg = (TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit) ? true : false;
            gv_IH.DynamicColumn.Add(new BoundColumn2("02", "Type", BoundColumnType2.DropDownList, 60, Align.Left, flg, "Type", InputType.None, new string[4] { "", "Hold发票", "解冻发票", "修改发票类型" }));
            gv_IH.DynamicColumn.Add(new BoundColumn2("00", "SOLD TO NO-SAP<br/>客户SAP编号", BoundColumnType2.TextBox, 100, Align.Left, flg, "Sap_Code", InputType.None, null));
            gv_IH.DynamicColumn.Add(new BoundColumn2("01", "Customer Name<br/>客户中文名称", BoundColumnType2.TextBox, 200, Align.Left, false, "Sold_CN_Name", InputType.None, null));
                      
            if (!Page.IsPostBack)
            {
                INFO.Text = string.Format("<br/>表单正在被同事“{0}”抢占处理，拒绝提交！", RobUser);
                INFO.Visible = IsOverFlow;
                InitControls();
                #region 发起步骤
                if (TaskAPI.IsInitiate)
                {

                }
                #endregion
                #region 审批环节
                else
                {
                    #region 加载数据并显示
                    mdc_spm_InvoiceHolding spm_Sales_1 = (mdc_spm_InvoiceHolding.process == TaskAPI.Process & mdc_spm_InvoiceHolding.incident == TaskAPI.Incident).ListFirst<mdc_spm_InvoiceHolding>();
                    if (spm_Sales_1 != null)
                    {
                        ApplicationNo.Text = spm_Sales_1.ApplicationNo.ToString();

                    }
                    #endregion

                    #region 审批项初始化
                    switch (TaskAPI.Step)
                    {
                        case "DMO Approve":
                        case "DMO Maintain":
                        case "DMO Check":
                            Assessment1.Option.Add(new t_AssessmentOption("Finish", "1", true));
                            Assessment1.Option.Add(new t_AssessmentOption("Return", "2", false));
                            break;
                    }
                    #endregion
                }
                #endregion

                #region 设置控件禁启用
                bool flg11 = (TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit) ? true : false;

                Assessment1.Enable = TaskAPI.IsAllowSubmit;

                SetVisible(flg11, Add, Delete);
                SetEnable(TaskAPI.Step == "DMO Maintain", SAP_Code);

                SetVisible(TaskAPI.IsAllowSubmit, Send, Split);
                Attachment1.AllowDelete = flg11;
                Attachment1.AllowUpload = flg11;
                //InitTabs();
                #endregion
            }

        }
        #endregion

        //protected override void OnLoad(EventArgs e)
        //{
        //    InitControls();
        //    base.OnLoad(e);
        //}

        public void InitControls()
        {

            gv_IH.Key = Key;
            #region 发起步骤
            if (TaskAPI.IsInitiate)
            {
                List<mdc_spm_InvoiceHolding> sales_1_s = new List<mdc_spm_InvoiceHolding>();
                for (int i = 0; i < 5; i++)
                {
                    sales_1_s.Add(new mdc_spm_InvoiceHolding());
                    //sales_1_s[i].ID = (i + 1).ToString();
                }
                gv_IH.DataSource = sales_1_s;
            }
            #endregion

            #region 审批环节
            else
            {
                IList<mdc_spm_InvoiceHolding> sales_1_s = (mdc_spm_InvoiceHolding.process == TaskAPI.Process & mdc_spm_InvoiceHolding.incident == TaskAPI.Incident).List<mdc_spm_InvoiceHolding>();
                if (sales_1_s.Count == 0)
                {
                    for (int i = 0; i < 5; i++)
                    {
                        sales_1_s.Add(new mdc_spm_InvoiceHolding());
                        //sales_1_s[i].ID = (i + 1).ToString();
                    }
                }
                gv_IH.DataSource = sales_1_s;
                
            }
            #endregion
        }
   

        #region 事件 Send
        protected void Send_Click(object sender, EventArgs e)
        {
            try
            {
                #region 数据验证
                if (TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {
                    List<string> vald_s = new List<string>();
                    vald_s.AddRange(DataValidation());
                    if (vald_s.Count > 0)
                    {
                        Anthem.Manager.AddScriptForClientSideEval(string.Format("ShowMessage(\"{0}\", {1});", CombineMessage(vald_s), vald_s.Count));
                        return;
                    }
                }
                #endregion

                #region 引擎传值
                if (TaskAPI.IsBeginStep)
                {
                    if ((TaskAPI.IsInitiate) && TaskAPI.IsAllowSubmit)
                    {
                        ApplicationNo.Text = Util.GenerateSequence(((object[])TaskAPI["PrefixNo"])[0].ToString() + "-" + System.DateTime.Now.ToString("yyMM"), "", 4);
                        TaskAPI.UserName = UserAPI.UserName;
                        TaskAPI["ApplicationNo"] = ApplicationNo.Text;
                        TaskAPI["ApplicatorName"] = UserAPI.UserFullName;
                        TaskAPI["Applicator"] = UserAPI.UserName;
                        TaskAPI["Time"] = System.DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
                        TaskAPI["ApplicatorEmail"] = UserAPI.Mail;
                        TaskAPI["Department"] = UserAPI.Department;
                        TaskAPI["ServerName"] = Util.AppSettings("ServerName");
                    }

                    TaskAPI.Summary =ApplicationNo.Text;//+ (VD.Checked ? " / Vendor " : "") + (SA.Checked ? " / Employee " : "");

                    //TaskAPI["Actions"] = VD_Category.SelectedValue;
                    TaskAPI["Remark_by_Initiator"] = Assessment1.Assessment.Remark;

                    #region 从数据库取得流程步骤处理人
                    SortedList<string, string> rec_a = new SortedList<string, string>();

                    IList<mdc_Recipient> rec_s = (mdc_Recipient.process == TaskAPI.Process & mdc_Recipient.status == 1
                                                         & mdc_Recipient.step.In(new string[3] { "DMO Approve", "DMO Maintain", "DMO Check" })).List<mdc_Recipient>();
                    foreach (mdc_Recipient rec in rec_s)
                    {
                        if (!rec_a.ContainsKey(rec.Step))
                        {
                            rec_a.Add(rec.Step, rec.Recipient);
                            continue;
                        }

                        if (rec_a.Values[rec_a.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                        {
                            continue;
                        }

                        rec_a[rec.Step] = rec_a.Values[rec_a.IndexOfKey(rec.Step)] + "," + rec.Recipient;
                    }

                    //步骤处理人赋值
                    for (int i = 0; i < rec_a.Keys.Count; i++)
                    {
                        TaskAPI["R_" + rec_a.Keys[i].Replace(" ", "_")] = rec_a.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    }
                    #endregion
                    #region RSM/RPM
                    //if (Keys.Items[0].Selected)
                    //{ 
                    if (TaskAPI.IsInitiate)
                    {
                        string division = "";
                        //List<string> cmd_tar = new List<string>();
                        List<string> cmd_tar3 = new List<string>();
                        //string region = VD_Region.SelectedValue.Length >= 3 ? VD_Region.SelectedValue.Substring(0, 3) : VD_Region.SelectedValue;

                        IList<mdc_Recipient> cmd_src = (mdc_Recipient.process == TaskAPI.Process & mdc_Recipient.step.In(new string[1] { "CA Check" })).List<mdc_Recipient>();

                        foreach (mdc_Recipient cmd_r in cmd_src)
                        {
                            if (!cmd_tar3.Contains(cmd_r.Recipient) && cmd_r.Step.ToUpper() == "CA CHECK")
                            {
                                if (cmd_r.Recipient == "#N/A") continue;
                                cmd_tar3.Add(cmd_r.Recipient);
                                continue;
                            }

                        }

                        //TaskAPI["R_RSM_RPM"] = cmd_tar.Count == 0 ? new string[1] { "" } : cmd_tar.ToArray();
                        TaskAPI["R_CA_Check"] = cmd_tar3.Count == 0 ? new string[1] { "" } : cmd_tar3.ToArray();
                    }
                    //}
                }
                    #endregion
                else
                {
                    TaskAPI["ApproveResult"] = Assessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                }

                //#region 退回步骤并返回功能传值  
                //if (!string.IsNullOrEmpty(Assessment1.JumpStep))
                //{
                //    TaskAPI["Step"] = Assessment1.JumpStep;
                //    TaskAPI["PreStep"] = TaskAPI.Step;
                //}
                //else
                //{
                //    string PreStep = ((object[])TaskAPI["PreStep"])[0].ToString();
                //    if (PreStep.Trim() != "")
                //    {
                //        TaskAPI["Step"]    = PreStep;
                //        TaskAPI["PreStep"] = "";
                //    }
                //    else
                //    {
                //        TaskAPI["Step"] = "";
                //        TaskAPI["PreStep"] = "";
                //    }
                //}
                //#endregion

                #endregion

                #region 提交步骤
                bool flg = false;
                Storage.TransactionExecute(o =>
                {
                    #region “Fill in the form”步骤
                    if (TaskAPI.IsBeginStep)
                    {
                        //mdc_spm_InvoiceHolding spm_Sales_1 = new mdc_spm_InvoiceHolding();
                        //if ((mdc_spm_InvoiceHolding.process == TaskAPI.Process & mdc_spm_InvoiceHolding.incident == TaskAPI.Incident & mdc_spm_InvoiceHolding.userName == UserAPI.UserName).Count<mdc_spm_InvoiceHolding>() > 0)
                        //{
                        //    spm_Sales_1 = (mdc_spm_InvoiceHolding.process == TaskAPI.Process & mdc_spm_InvoiceHolding.incident == TaskAPI.Incident & mdc_spm_InvoiceHolding.userName == UserAPI.UserName).ListFirst<mdc_spm_InvoiceHolding>();
                        //}
                        //else
                        //{
                        //    spm_Sales_1.Process = TaskAPI.Process;
                        //    spm_Sales_1.Incident = TaskAPI.Incident;
                        //    spm_Sales_1.UserName = UserAPI.UserName;
                        //    //spm_Sales_1.UserFullName = UserAPI.UserFullName;
                        //    spm_Sales_1.ApplicationNo = ApplicationNo.Text;
                        //    spm_Sales_1.Time = System.DateTime.Now;
                        //    spm_Sales_1.Status = 0;
                        //    spm_Sales_1.Department = UserAPI.Department;
                        //}

                        //spm_Sales_1.Actions = VD_Category.SelectedItem.Text;
                        (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });

                       //Storage.Save(Storage.Context1, spm_Sales_1);
                    }
                    #endregion
                    Save();

                    #region “DMO Maintain”步骤
                    //if (TaskAPI.Step == "DMO Maintain")
                    //{
                    //    (mdc_spm_Sales_Gv.process == TaskAPI.Process & mdc_spm_Sales_Gv.incident == TaskAPI.Incident).Edit<mdc_spm_Sales_Gv>(p =>
                    //    {
                    //       // p.SAP_Code = SAP_Code.Text;
                    //    }    
                    //    );
                    //}
                    #endregion

                    Storage.Save(Assessment1.Assessment);    //审批意见
                    #region 退回步骤并返回功能 传值
                    if (TaskAPI["R_" + TaskAPI.Step.Replace(" ", "_").Replace("/", "_")] != null)
                    {
                        object[] obj = (object[])(TaskAPI["R_" + TaskAPI.Step.Replace(" ", "_").Replace("/", "_")]);
                        for (int i = 0; i < obj.GetUpperBound(0); i++)
                        {
                            obj[i] = null;
                        }
                        obj[0] = UserAPI.UserName;
                        TaskAPI["R_" + TaskAPI.Step.Replace(" ", "_")] = obj;
                    }
                    //多节点退回
                    if (!string.IsNullOrEmpty(Assessment1.JumpStep))
                    {
                        Assessment1.SetAsReturn(true);
                        TaskAPI.DirectActive(Assessment1.JumpStep);
                    }
                    else
                    {
                        Assessment1.SetAsReturn(false);
                    }
                    Assessment1.SubmitTo();
                    #endregion
                    flg = TaskAPI.Send();
                });

                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.IsInitiate)
                {
                    (mdc_spm_InvoiceHolding.process == TaskAPI.Process & mdc_spm_InvoiceHolding.incident == 0 & mdc_spm_InvoiceHolding.userName == UserAPI.UserName).Edit<mdc_spm_InvoiceHolding>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
 
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.userName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

 


                }
                #endregion

                Send.Visible = false;
                Anthem.Manager.AddScriptForClientSideEval("JSInfomation('" + Resources.Global.C_00_Success + "',true)");
            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用NVA方法Send_Click出错：" + ex.ToString());
                Anthem.Manager.AddScriptForClientSideEval("JSInfomation('" + Resources.Global.C_00_Failed + "',false)");
            }

        }
        #endregion
        #region 方法 Save(保存数据库)
        public void Save()
        {
            //if (!Status.IsEdited)
            //{
            //    return;
            //}
            foreach (mdc_spm_InvoiceHolding sales_1 in (List<mdc_spm_InvoiceHolding>)gv_IH.DataSource)
            {

                if (string.IsNullOrEmpty(sales_1.Sap_Code) && string.IsNullOrEmpty(sales_1.Type))
                {
                    continue;
                }
                if (TaskAPI.IsBeginStep)
                {
                    sales_1.Process = TaskAPI.Process;
                    sales_1.Incident = TaskAPI.Incident;
                    sales_1.UserName = UserAPI.UserName;
                    sales_1.ApplicationNo = ApplicationNo.Text;
                    sales_1.Department = UserAPI.Department;
                }
                sales_1.Time = System.DateTime.Now;
                sales_1.Status = 1;
                Storage.Save(sales_1);
            }
        }
        #endregion
        #region 事件 Add(增加行)
        protected void Add_Click(object sender, EventArgs e)
        {
            List<mdc_spm_InvoiceHolding> sefi_1_s = (List<mdc_spm_InvoiceHolding>)gv_IH.DataSource;
            mdc_spm_InvoiceHolding sefi_1 = new mdc_spm_InvoiceHolding();
            //sefi_1.ID = sefi_1_s.Count + 1;
            sefi_1_s.Insert(sefi_1_s.Count, sefi_1);
            gv_IH.DataSource = sefi_1_s;
            gv_IH.DataBind();
        }
        #endregion
        #region 事件 Delete(删除行)
        protected void Delete_Click(object sender, EventArgs e)
        {
            List<mdc_spm_InvoiceHolding> base_1_s = (List<mdc_spm_InvoiceHolding>)gv_IH.DataSource;
            IList<mdc_spm_InvoiceHolding> base1 = (mdc_spm_InvoiceHolding.process == TaskAPI.Process & mdc_spm_InvoiceHolding.incident == TaskAPI.Incident).List<mdc_spm_InvoiceHolding>();
            if (base_1_s.Count == 1)
            {

                Anthem.Manager.AddScriptForClientSideEval("JSInfomation('至少保留最后一个 Sheet ！',false)");
                return;
 
            }
            base_1_s.RemoveAt(gv_IH.ChangedRowIndex == -1 || gv_IH.ChangedRowIndex >= base_1_s.Count ? base_1_s.Count - 1 : gv_IH.ChangedRowIndex);
            bool flag = false;
            foreach (mdc_spm_InvoiceHolding base_1 in base1)
            {

                foreach (mdc_spm_InvoiceHolding base_2 in base_1_s)
                {
                    if (base_2.ID == base_1.ID)
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    Storage.Delete(base_1);
                }
                flag = false;
            }
            gv_IH.DataSource = base_1_s;
            gv_IH.DataBind();

        }
        #endregion
        #region 方法 gv_IH 数据取得
        protected void gv_IH_DataBinding(object sender, EventArgs e)
        {
            //if (TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit && gv_CCC_1.ChangedColumnIndex == 9)
            //if (TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit && (gv_Sales_1.ChangedColumnIndex == 0 || gv_Sales_1.ChangedColumnIndex == 1))
            H2.NET.Controls.GridView gv = (H2.NET.Controls.GridView)sender;
            //string id = gv.ID.ToString();
            //if (id == "gv_Sales_K1")
            //{
            List<mdc_spm_InvoiceHolding> ccc_s = gv_IH.DataSource as List<mdc_spm_InvoiceHolding>;
            if ((TaskAPI.IsBeginStep) && TaskAPI.IsAllowSubmit && gv.ChangedColumnIndex == 1)
            {
                foreach (mdc_spm_InvoiceHolding ccc in ccc_s)
                {
                    m_Customer ncc = (m_Customer.customerCode == ccc.Sap_Code).ListFirst<m_Customer>();
                    if (ncc != null)
                    {
                        ccc.Sold_CN_Name = ncc.CustomerName;
                    }
                    else
                    {
                        ccc.Sold_CN_Name = "";
                    }
                }
            }
               
  
        }
        #endregion
        #region 方法 数据验证
        private List<string> DataValidation()
        {
            #region
            List<Regular> regs = new List<Regular>();
           
            int i = 1;
            foreach (mdc_spm_InvoiceHolding ccc in (List<mdc_spm_InvoiceHolding>)this.gv_IH.DataSource)
            {
                if (string.IsNullOrEmpty(ccc.Sap_Code)&&string .IsNullOrEmpty(ccc.Type))
                {
                    continue;
                }

                regs.Add(new Regular(RegularExp.NotEmpty, (ccc.Sap_Code+"").Trim(), "&nbsp;&nbsp;行" + i + ": 客户编号为必填"));
                regs.Add(new Regular(RegularExp.NotEmpty, (ccc.Type + "").Trim(), "&nbsp;&nbsp;行" + i + ": 发票类型为必填"));
                TextBox remark = (TextBox)Assessment1.FindControl("Remark");
                regs.Add(new Regular(RegularExp.NotEmpty, (remark.Text + "").Trim(), "备注信息必须填写"));
                i++;
            }
            if (i == 1)
            {
                t_Attachment list = (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == TaskAPI.Incident).ListFirst<t_Attachment>();
                if (list == null)
                {
                    regs.Add(new Regular(RegularExp.NotEmpty, list, "&nbsp;&nbsp;" + "表单不能为空或者必须上传附件！"));
                }
                //Repeater repeater = (Repeater)Attachment1.FindControl("rep_Attachment");
                //foreach (RepeaterItem rep in repeater.Items)
                //{
                //    string FileName = ((Label)rep.FindControl("lbl_FileName")).Text.ToString();
                //    regs.Add(new Regular(RegularExp.NotEmpty, FileName, "&nbsp;&nbsp;" + "表单不能为空或者必须上传附件！mm"));
                //}

            }
            #endregion



            return Validation(regs);
        }
        #endregion

        #region 方法 Others
        protected void VD_Payment_Methods_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private string getFormCheckList(Anthem.CheckBoxList ck)
        {
            string t = "";
            for (int i = 0; i < ck.Items.Count; i++)
                if (ck.Items[i].Selected)
                    t += "," + ck.Items[i].Value;
                else
                    t += ",";
            return t;
        }
        private Anthem.CheckBoxList setCheckList(string t, Anthem.CheckBoxList ck)
        {
            try
            {
                string[] tt = t.Split(',');

                for (int i = 0; i <= tt.GetUpperBound(0); i++)
                {
                    for (int j = 0; j < ck.Items.Count; j++)
                    {
                        if (ck.Items[j].Value == tt[i].ToString())
                        { ck.Items[j].Selected = true; break; }
                    }
                }
            }
            catch { }
            return ck;
        }
        #endregion
 


    }
}
 